const { pathToRegexp } = require("path-to-regexp");

const whiteList = [
  pathToRegexp("/api/user/login"),
  pathToRegexp("/api/user/resigister"),
  pathToRegexp("/resources/*"),
];
const jwt = require("../utils/jwtHelp");
// 权限验证中间件
module.exports = (req, res, next) => {
  console.log("req.path", req.path);
  console.log("whiteList", whiteList.includes(req.path));
  if (whiteList.some((item) => item.test(req.path))) {
    console.log("whiteList pass");
    next();
    return;
  }
  const arr = req.headers.authorization.split(" ");
  console.log("arr", arr);
  const token = arr[1];
  if (token) {
    const flag = jwt.verify(token);
    if (flag) {
      next();
    } else {
      res.status(401).send({
        code: 401,
        msg: "token is invalid",
        data: null,
      });
    }
  } else {
    res.status(401).send({
      code: 401,
      msg: "token is invalid",
      data: null,
    });
  }
};
